import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { BtnNaviSharedService } from 'src/app/services/btn-navi-shared.service';
import { MemberStorageService } from 'src/app/services/member-storage.service';
import { MemberService } from 'src/app/services/member.service';
import { UtilService } from 'src/app/services/util.service';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-registe',
  templateUrl: './registe.component.html',
  styles: [``]
})
export class RegisteComponent implements OnInit {
  public member: any = {
    names: '',
    nickname: '',
    newPswd: '',
    pswdConfirm: '',
    inviteCode: '',
    agreed: true,
    token: '',
    ip: '127.0.0.1'
  };
  //是否开启了邀请码:全局设置
  public activeInvite: boolean = environment.registeInvite;
  public errorMessage: string = '';

  constructor(
    private title: Title,
    private router: Router,
    private memberService: MemberService,
    private memberStorage: MemberStorageService,
    private util: UtilService,
    private btnNaviSharedService: BtnNaviSharedService) {
    this.btnNaviSharedService.active(false); //不显示全局的导航
    this.member.token = this.util.randomAlphaNumeric(8) || '123456';
    this.memberStorage.getIpCliente().subscribe(ipAddr=>this.member.ip = ipAddr);
  }

  ngOnInit(): void {
    //在线的情况下注册无意义
    if(this.memberStorage.get() !== null){
      this.router.navigate(['/home']);
    }
    this.title.setTitle('一起来分享身边的大事件吧');
  }

  public createMember(submitBtn: HTMLButtonElement) {
    submitBtn.disabled = true;
    submitBtn.setAttribute('value', '请稍后...');
    //
    this.memberService.signUp(
      this.member.names,
      this.member.pswdConfirm,
      this.member.nickname,
      this.member.inviteCode,
      this.member.token,
      this.member.ip).subscribe({
        next: response => {
          if (response.id > 0) {
            this.router.navigate(['/member/login']);
          }
          this.errorMessage = '注册失败';
        },
        error: err => {
          if (err instanceof HttpErrorResponse) {
            if (err.error instanceof ErrorEvent) {
              this.errorMessage = err.error.message;
            } else {
              this.errorMessage = (err.status === 400) ? err.error : '会员注册失败';
            }
          } else if (err instanceof Error) {
            this.errorMessage = err.message;
          } else { this.errorMessage = err; }
          //
          submitBtn.disabled = false;
          submitBtn.setAttribute('value', '免费注册');
        },
        complete: () => { console.log('[MemberRegister-CTL]Completed'); }
      });
  }
}
